<script setup lang="tsx">
import { ref } from 'vue';
import type { Ref } from 'vue';
import { NButton, NPopconfirm, NTag } from 'naive-ui';
import { useBoolean } from '@sa/hooks';
import { useAppStore } from '@/store/modules/app';
import { useTable, useTableOperate } from '@/hooks/common/table';
import { $t } from '@/locales';
import { yesOrNoRecord } from '@/constants/common';
import SvgIcon from '@/components/custom/svg-icon.vue';
import { fetchGetUserRoutes, getSubmitParams, deleteMenu, getUpdateParams } from '@/service/api/route';

const appStore = useAppStore();

const { bool: visible, setTrue: openModal } = useBoolean();

const wrapperRef = ref<HTMLElement | null>(null);
const title = ref('');
const model = ref({
  title: '',
  name: '',
  url: '',
  condition: '',
  icon: '',
  weigh: 0,
  ismenu: 1,
  pid: 0,
  id: 0,
});
const rules = {};
const { columns, columnChecks, data, loading, pagination, getData, getDataByPage } = useTable({
  apiFn: fetchGetUserRoutes,
  columns: () => [
    {
      key: 'id',
      title: 'ID',
      align: 'center',
      width: 100,
    },
    {
      key: 'title',
      title: '菜单名称',
      align: 'center',
      width: 250,
      // render: row => {
      //   const { name } = row;
      //   return <span>{name}</span>;
      // }
    },
    {
      key: 'icon',
      title: '图标',
      align: 'center',
      width: 60,
      render: row => {
        return (
          <div class="flex-center">
            <SvgIcon icon={row.icon} class="text-icon" />
          </div>
        );
      }
    },
    {
      key: 'name',
      title: '路由名称',
      align: 'center',
      width: 220
    },
    {
      key: 'url',
      title: '路由路径',
      align: 'center',
      minWidth: 220
    },
    {
      key: 'ismenu',
      title: '是否为菜单',
      align: 'center',
      width: 120,
      render: row => {
        const ismenu: CommonType.YesOrNo = row.ismenu ? 'Y' : 'N';

        const tagMap: Record<CommonType.YesOrNo, NaiveUI.ThemeColor> = {
          Y: 'error',
          N: 'default'
        };

        const label = $t(yesOrNoRecord[ismenu]);

        return <NTag type={tagMap[ismenu]}>{label}</NTag>;
      }
    },
    {
      key: 'condition',
      title: '路由组件',
      align: 'center',
      width: 200,
    },
    {
      key: 'weigh',
      title: '排序',
      align: 'center',
      width: 200
    },
    {
      key: 'operate',
      title: '操作',
      align: 'center',
      width: 230,
      render: row => (
        <div class="flex-center justify-end gap-8px">
          {row.pid == 0 && (
            <NButton type="primary" ghost size="small" onClick={() => handleAddChildMenu(row)}>
              添加子菜单
            </NButton>
          )}
          <NButton type="primary" ghost size="small" onClick={() => handleEdit(row)}>
            编辑
          </NButton>
          <NPopconfirm onPositiveClick={() => handleDelete(row.id)}>
            {{
              default: () => '确定删除吗？',
              trigger: () => (
                <NButton type="error" ghost size="small">
                  删除
                </NButton>
              )
            }}
          </NPopconfirm>
        </div>
      )
    }
  ]
});

const { checkedRowKeys, onBatchDeleted, onDeleted } = useTableOperate(data, getData);

const operateType = ref('add');

function handleAdd() {
  operateType.value = 'add';
  title.value = '新增菜单';
  pname.value = '顶级菜单';
  // 清空model
  model.value = {
    title: '',
    name: '',
    url: '',
    condition: '',
    icon: '',
    weigh: 0,
    ismenu: 1,
    pid: 0,
  };
  openModal();
}

async function handleDelete(id: number) {
  // request
  const { response } = await deleteMenu(id);
  console.log(response);
  if (response.data.code == 1) {
    window.$message?.success(response.data.msg);
    getData();
  } else {
    window.$message?.error(response.data.msg);
  }
}

function handleEdit(item) {
  operateType.value = 'edit';
  title.value = '编辑菜单';
  model.value = { ...item };
  console.log(item);
  if (item.pid == 0) {
    pname.value = '顶级菜单';
    model.value.pid = 0;
  } else {
    //查询出数组中匹配的,是多维数组
    const p = data.value.find(v => v.id == item.pid);
    if (p) {
      pname.value = p.title;
      model.value.pid = p.id;
    } else {
      pname.value = '顶级菜单';
      model.value.pid = 0;
    }

  }
  openModal();
}

function handleAddChildMenu(item) {
  operateType.value = 'addChild';
  // 清空model
  model.value = {
    title: '',
    name: '',
    url: '',
    condition: '',
    icon: '',
    weigh: 0,
    ismenu: 1,
    pid: 0,
    id: 0,
  };
  pname.value = item.title;
  model.value.pid = item.id;
  console.log(item);
  openModal();
}
function init() {
}

// init
init();
async function handleSubmit() {
  if (operateType.value == 'addChild' || operateType.value == 'add') {
    var res = await getSubmitParams(model.value);
  } else {
    var res = await getUpdateParams(model.value);
  }
  console.log('response: ', res.response);
  if (res.response.data.code == 1) {
    window.$message?.success(res.response.data.msg);
    visible.value = false;
    getData();
  } else {
    window.$message?.error(res.response.data.msg);
  }

}
const pname = ref('');
</script>

<template>
  <div ref="wrapperRef" class="flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <NCard title="菜单管理" :bordered="false" size="small" class="sm:flex-1-hidden card-wrapper">
      <template #header-extra>
        <TableHeaderOperation v-model:columns="columnChecks" :disabled-delete="checkedRowKeys.length === 0"
          :loading="loading" @add="handleAdd" @refresh="getData" />
      </template>
      <NDataTable v-model:checked-row-keys="checkedRowKeys" :columns="columns" :data="data" size="small"
        :flex-height="!appStore.isMobile" :scroll-x="1088" :loading="loading" :row-key="row => row.id" remote
        :pagination="pagination" class="sm:h-full" />
    </NCard>
    <NModal v-model:show="visible" :title="title" preset="card" class="w-800px">
      <NScrollbar class="h-480px pr-20px">
        <NForm ref="formRef" :model="model" :rules="rules" label-placement="left" :label-width="100">
          <NGrid responsive="screen" item-responsive>

            <NFormItemGi span="24" label="父级菜单" path="pid">
              <NInput v-model:value="pname" placeholder="" disabled />
            </NFormItemGi>

            <NFormItemGi span="24 m:12" label="菜单类型" path="ismenu">
              <NRadioGroup v-model:value="model.ismenu">
                <NRadio :value="1" label="菜单" />
                <NRadio :value="0" label="接口" />
              </NRadioGroup>
            </NFormItemGi>
            <NFormItemGi span="24" :label="model.ismenu == 1 ? '菜单名称' : '接口名称'" path="title">
              <NInput v-model:value="model.title" placeholder="请输入" />
            </NFormItemGi>
            <NFormItemGi span="24" :label="model.ismenu == 1 ? '路由名称' : '接口地址'" path="name">
              <NInput v-model:value="model.name" placeholder="请输入" />
            </NFormItemGi>
            <template v-if="model.ismenu == 1">
              <NFormItemGi span="24" label="路由路径" path="url">
                <NInput v-model:value="model.url" placeholder="请输入" />
              </NFormItemGi>
              <NFormItemGi span="24" label="路由组件" path="condition">
                <NInput v-model:value="model.condition" placeholder="请输入" />
              </NFormItemGi>
              <NFormItemGi span="24 m:12" label="icon" path="icon">
                <NInput v-model:value="model.icon" placeholder="请输入icon" />
              </NFormItemGi>
            </template>
            <NFormItemGi span="24 m:12" label="排序" path="weigh">
              <NInput type="number" v-model:value="model.weigh" placeholder="请输入排序" />
            </NFormItemGi>
          </NGrid>
        </NForm>
      </NScrollbar>
      <template #footer>
        <NSpace justify="end" :size="16">
          <NButton @click="visible = false">取消</NButton>
          <NButton type="primary" @click="handleSubmit">确认</NButton>
        </NSpace>
      </template>
    </NModal>
  </div>
</template>

<style scoped></style>
